%%--------------------------------------------------------------------
%% Author: <vjache>
%% Created: 30.03.2009
%% Description: Iterator that switches to defult one if and only if
%%				base iterator an empty one.
%%--------------------------------------------------------------------
-module(iter_on_empty).

%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("../include/iter.hrl").
%%--------------------------------------------------------------------
%% Exported Functions
%%--------------------------------------------------------------------
-export([
		 new/2,
		 open/1,
		 next/1,
		 close/1,
		 test/0
		 ]).

%%--------------------------------------------------------------------
%% API Functions
%%--------------------------------------------------------------------

%%--------------------------------------------------------------------
%% Function: 	new(Iter,DefaultIter) -> iter()
%% Description: Creates a iter specification that wraps a base iter (Iter).
%%				If base iter is an empty one than default iter will be used, 
%%				otherwise only base iter will be used.
%%--------------------------------------------------------------------
new(Iter,DefaultIter) ->
	iter:from_module(?MODULE, {Iter,DefaultIter}).

open({Iter,DefaultIter}) ->
	IterState=iter:open(Iter),
	case iter:next(IterState) of
		{FinState,?EOF} ->
			ok=iter:close(FinState),
			{iter:open(DefaultIter)};
		{_IterStateNew,_Item}=R ->
			R
	end.

next({IterState,Item}=_S) ->
	{{IterState},Item};
next({IterState}=_S) ->
	{IterStateNew,Item}=iter:next(IterState),
	{{IterStateNew},Item}.
close({IterState,_Item}=_S) ->
	ok=iter:close(IterState);
close({IterState}=_S) ->
	ok=iter:close(IterState).

%%--------------------------------------------------------------------
%% Test Functions
%%--------------------------------------------------------------------

test() ->
	I=new(iter:from_list([]),iter:single('NULL')),
	iter:foreach(I,fun(E)->
						   io:format("~p~n",[E])
				 end),
	ok.

%%--------------------------------------------------------------------
%% Local Functions
%%--------------------------------------------------------------------